<template>
	<!-- 钻石商城  diamondMall-->
	<view class="">
		<view class="diamondMall_head flex1 flex-between p20">
			<view class="">
				<u-icon @click=backhomeindex() class="size-40" name="arrow-left"></u-icon>
			</view>
			<view class="size-30 fw ml-60 mycustomer_head">
				{{name}}
			</view>
			<view class="">
				<u-icon @click="friendDetail(user_id,list_id,show_name)" class="size-40" name="more-dot-fill"></u-icon>
			</view>
		</view>
		<view class="" style="background-color: rgb(240, 239, 244);">
			<scroll-view scroll-with-animation="true" style="height: 1100rpx;" scroll-y="true" :scroll-top="scrollTop">
				<view class="numbersbox flex flex-start ptb-10 plr-10" v-if="this.name=='群聊'">

					<image :src="'http://im.ezongguan.com/static/photo/'+item.photo" mode="" v-for="item in numberList">
					</image>
				</view>

				<view class=" mt-60 p10  " v-for="(item,index) in chatMessages" style="" @longpress="longpress(item)">

					<view :style="{float:item.msg.user_info.uid ==obj?'left':'right'}" class="flex1"
						style="align-items: center;">
						<image v-if="item.msg.user_info.uid==obj" class=""
							:src="'http://im.ezongguan.com/static/photo/' +item.msg.user_info.face" mode=""
							style="width: 60rpx;height: 60rpx;border-radius: 50%;">
						</image>
						<view class="size-26"
							style="background-color: #ECECEC;padding: 20rpx;border-radius: 20rpx 0px 20rpx 20rpx;margin: 0 20rpx 0px 20rpx;word-wrap: break-word;word-break: normal;max-width: 460rpx;">
							{{item.msg.content.text}}
						</view>
						<image v-if="item.msg.user_info.uid!=obj" class=""
							:src="'http://im.ezongguan.com/static/photo/' +item.msg.user_info.face" mode=""
							style="width: 60rpx;height: 60rpx;border-radius: 50%;">
						</image>

					</view>
				</view>

			</scroll-view>
		</view>
		<view class="mycustomer_bottom flex1"
			style="align-items: center;justify-content: space-evenly;background-color: #E9E9E9;">
			<view class="">
				<image :src="luyinsrc" mode="widthFix" style="width: 50rpx;" @click="record"></image>
			</view>
			<view class="">
				<input maxlength=99999 @input="handleInput" v-model="value1" @confirm=enter :placeholder=placeholder
					placeholder-style='text-align:center' :disabled="disabled"
					style="background-color: #FFF;width: 500rpx;height: 60rpx;;border-radius: 10rpx;margin: 0 0 0 0;" />
			</view>
			<view class="">
				<image src="../../static/my/my_weixiao.png" mode="widthFix" style="width: 50rpx;"></image>
			</view>
			<view class="">
				<image src="../../static/my/my_jiahao.png" mode="widthFix" style="width: 50rpx;"></image>
			</view>
		</view>
		<u-popup v-model="show" mode="center" :mask='false'>
			<view class="p10" style="line-height: 60rpx;">
				<view :class="[item.active==true?'selectitem':'selectitem1']" v-for="item in ribbonlist"
					@click="handleribbonlist(item)">
					{{item.name}}
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
	export default {
		components: {},
		data() {
			return {
				setIntervalist: '',
				ribbonlist: [{
						name: '复制',
						id: 0,
						active: 'flase'
					},
					{
						name: '发送给朋友',
						id: 1,
						active: 'flase'
					}, {
						name: '收藏',
						id: 2,
						active: 'flase'
					}, {
						name: '删除',
						id: 3,
						active: 'flase'
					}, {
						name: '多选',
						id: 4,
						active: 'flase'
					}, {
						name: '撤回',
						id: 5,
						active: 'flase'
					},
				],
				show: false,
				disabled: false,
				luyinsrc: '../../static/my/my_luyin.png',
				placeholder: '',
				time: 0,
				obj: '',
				pageList: [],
				pageList1: [],
				pageList2: [],
				valueInput: '',
				value1: '',
				scrollTop: 0,
				list_id: '',
				name: '',
				numberList: '',
				chatMessages: [],
				user_id: '',
				show_name: ',',
				// timeout: 10000,
				// timeoutObj: null,
				socketOpen: false,
				socketid:'',

			}

		},
		onShow() {
			// this.getMemberPhotos()
			// this.getChatDetails()
			// this.chatData()
			// this.setchat()
			// this.openConnection()
			// this.onSocketMessage()
		},
		onPageScroll: function(e) { //nvue暂不支持滚动监听，可用bindingx代替
			// console.log("滚动距离为：" + e.scrollTop);
		},
		onLoad(options) {
			// console.log(options);
			this.list_id = options.list_id
			this.show_name = options.show_name
			// console.log(this.show_name);
		},
		onHide() {
			// clearInterval(this.setIntervalist)
			// this.setIntervalist = null
			// console.log('onHide');
		},	
		onUnload() {
			// clearInterval(this.setIntervalist)
			// this.setIntervalist = null
			// console.log('onUnload');
		},
		created() {
			this.getMemberPhotos()
			this.getChatDetails()
			this.openConnection()
			this.onSocketMessage()
			this.chatData()
		},
		methods: {
			// Websocket
			openConnection() {
				// 打开连接
				// uni.closeSocket(); // 确保已经关闭后再重新打开
				uni.connectSocket({
					url: 'ws://im.ezongguan.com:8383',
					success(res) {
						console.log('WebSocket连接成功 connectSocket=', res);
					},
					fail(err) {
						console.log('WebSocket连接失败 connectSocket=', err);
					}
				});
				 
				//监听连接成功
				uni.onSocketOpen(res => {
					// this.onSocketMessage(); // 打开成功监听服务器返回的消息
					// this.socketOpen = false;
					this.socketOpen = true;
					// this.code = 'WebSocket连接成功';
					// console.log('WebSocket连接成功');
					// let data = {
					// 	content: '你好',
					// 	mode: 'heart',
						 
					// }
					//连接成功就发检测
					//1008的报错，1000是正确
					//心跳检测成功后发消息绑定
					// 通过 WebSocket 连接发送数据
					uni.sendSocketMessage({
						data: "test"
						// data: JSON.stringify('data'),
						// success: res => {
						// 	console.log('连接中....');
						// 	data.mode = 'accept'
						// 	uni.sendSocketMessage({
						// 		data: JSON.stringify(data),
						// 		success: res => {
						// 			console.log('连接中....绑定成功',res);
						// 		},
						// 	});
						// },
						// fail: err => {
						// 	console.log('连接失败重新连接....');
						// }
					});
				});
				// uni.onSocketError(res => {
				// 	this.code = '连接打开失败';
				// 	console.log('WebSocket连接打开失败，请检查！');
				// });
				// uni.onSocketClose(res => {
				// 	this.code = '连接已关闭';
				// 	// clearInterval(this.timeoutObj);
				// 	console.log('WebSocket 已关闭！');
				// });
			 
			},
			//	打开成功监听服务器返回的消息  监听WebSocket接受到服务器的消息事件
			onSocketMessage() {
				// console.log(111);
				// 消息
				// this.timeout = 10000;
				// this.timeoutObj = null;
				//监听WebSocket连接打开事件。
				uni.onSocketMessage(res => {
					console.log("onSocketMessage", res);
					// this.socketid=JSON.parse(res.data).data.client_id
					// this.socketOpen = true;
					this.getSocketMsg(JSON.parse(res.data)); // 监听到有新服务器消息
				});
			},
			// 监听到有新服务器消息
			getSocketMsg(reData) { 
				// 监听到服务器消息
				console.log('reData', reData);
				// console.log('收到服务器消息', reData.data.client_id);
				// if (reData.errcode == 1000) {
				// 	this.code = '连接中'
				// } else if (reData.errcode == 1008) {
				// 	this.code = '连接断开'
				// }
				// this.reset(); // 检测心跳reset,防止长时间连接导致连接关闭
			},
			// 检测心跳reset
			reset() {
				// clearInterval(this.timeoutObj);
				this.start(); // 启动心跳
			},
			// 启动心跳 start
			start() {
				let data = {
					content: '你好',
					mode: 'heart',
					user_id: this.list_id
				}
				// this.timeoutObj = setInterval(() => {
					//1008的报错，1000是正确
					uni.sendSocketMessage({
						data: JSON.stringify(data),
						success: res => {
							console.log('连接中....');
							this.chatData()
							 
						},
						fail: err => {
							console.log('连接失败重新连接....');
							this.openConnection();
						}
					});
				// }, this.timeout);
			},
			// setchat() {
			// 	this.setIntervalist=setInterval(() => {
			// 		this.chatData()
			// 	}, 30000)
			// },
			// Websocket

			// 撤回
			withdraw() {
				console.log(this.msg_id);
				this.msg_id = this.msg_id
				var params = {
					list_id: this.list_id,
					_token: uni.getStorageSync('im_token'),
					_agent_id: '1',
					msg_id: this.msg_id,
					type: '0'
				}
				uni.request({
					url: `http://im.ezongguan.com/im/message/withdraw`,
					method: 'POST',
					data: params,
					success: (res) => {
						console.log(res)
						if (res.data.err == 1) {
							uni.showToast({
								title: res.data.msg,
								icon: 'none'
							})
						} else if (res.data.err == 0) {
							uni.showToast({
								title: res.data.msg,
								icon: 'none'
							})
						}
					},
				})
				this.chatData()
			},
			// 功能区按钮事件
			handleribbonlist(item) {
				console.log(item);
				this.ribbonlist.forEach((item) => {
					item.active = false
				})
				item.active = true
				if (item.id == 5) {
					this.withdraw()
				}
			},
			// 长按功能区事件
			longpress(item) {
				console.log(item.msg.id);
				this.msg_id = item.msg.id
				console.log(111);
				this.show = true
			},
			record() {
				this.time++
				console.log(this.time)
				if ((this.time) % 2 == 0) {
					this.luyinsrc = '../../static/my/my_luyin.png'
					this.placeholder = ''
					this.disabled = false
					console.log(1);
				} else {
					this.luyinsrc = '../../static/my/my_luyin1.png'
					this.placeholder = '按住说话'
					this.disabled = true
					console.log(2);
				}
			},
			// 右上控件
			friendDetail(user_id, list_id, show_name) {
				uni.navigateTo({
					url: '../chip/friendDetail?user_id=' + user_id + '&list_id=' + list_id + '&show_name=' +
						show_name
				})
			},
			// 获得当前会话内容
			chatData() {
				// this.getChatDetails()
				var params = {
					list_id: this.list_id,
					_token: uni.getStorageSync('im_token'),
					_agent_id: '1',
					time: 0,
					is_up: 1
				}
				uni.request({
					url: `http://im.ezongguan.com/im/get/chatData`,
					method: 'POST',
					data: params,
					success: (res) => {
						// this.numberList=res.data.data
						this.chatMessages = res.data.data.list
						this.obj = res.data.data.obj_id
						// console.log(this.obj); 
						// console.log(this.chatMessages)
						this.pageList1 = []
						this.pageList2 = []
						for (let i = 0; i < this.chatMessages.length; i++) {
							// console.log(this.chatMessages[i].msg.user_info.uid,"user_info.uid")
							// console.log(this.user_id,"user_id")
							if (this.chatMessages[i].msg.user_info.uid == this.obj) {
								this.pageList1.push(this.chatMessages[i])
							} else {
								this.pageList2.push(this.chatMessages[i])
							}

							// console.log(this.pageList1)
							// console.log(this.pageList2)
						}
					},
				})
			},
			// 会话窗口获取成员头像
			getMemberPhotos() {
				var params = {
					list_id: this.list_id,
					_token: uni.getStorageSync('im_token'),
					_agent_id: '1'
				}
				uni.request({
					url: `http://im.ezongguan.com/im/vendor/getMemberPhotos`,
					method: 'POST',
					data: params,
					success: (res) => {
						this.numberList = res.data.data
						// console.log(this.numberList)
					},
				})
			},
			// 获得会话详情
			getChatDetails() {
				var params = {
					list_id: this.list_id,
					_token: uni.getStorageSync('im_token'),
					_agent_id: '1'
				}
				uni.request({
					url: `http://im.ezongguan.com/im/message/getChatDetails`,
					method: 'POST',
					data: params,
					success: (res) => {
						// console.log(res)
						if (res.data.data.group.name == '群聊') {
							this.name = res.data.data.group.name
						} else {
							this.name = res.data.data.member[1].show_name
							this.user_id = res.data.data.member[1].user_id
						}

					},
				})
			},
			// 聊天页面回退到消息中心
			backhomeindex() {
				uni.switchTab({
					url: "/pages/chip/index"
				})
			},
			// 聊天界面回车事件
			handleInput(e) {
				// this.valueInput = e.detail.value
				// console.log(this.valueInput)
			},
			// 发送事件
			enter(e) {
				// console.log(e);
				this.valueInput = e.detail.value
				console.log(this.valueInput);
				this.value1 = null	   
				var params = {
					_token: uni.getStorageSync('im_token'),
					_agent_id: '1',
					content_type: 0,
					content: `{"text":"${this.valueInput}"}`,
					list_id: this.list_id,
				}
				uni.request({
					url: `http://im.ezongguan.com/im/message/textMsg`,
					method: 'POST',
					data: params,
					success: (res) => {
						console.log(res)  
						
						if (this.socketOpen) {
							console.log("this.socketOpen", this.socketOpen)
							uni.sendSocketMessage({
								  data: this.valueInput,
							}) 
							this.chatData()
						} else{
							console.log("this.socketOpen", this.socketOpen)
							uni.onSocketOpen(res => {
								this.socketOpen = true;
								uni.sendSocketMessage({
									  data: this.valueInput,
								}) 
							})
							this.chatData()
						}
					},
				})
				// uni.sendSocketMessage({
				// 	  data: JSON.stringify(e),
				// }) 
			}

		}
	}
</script>

<style lang="less" scoped>
	page {
		background-color: #FFF;
	}

	.selectitem {
		color: skyblue;
	}

	.selectitem1 {
		color: #000;
	}

	.numbersbox {
		background-color: #fff;

		image {
			width: 80rpx;
			height: 80rpx;
			margin-right: 20rpx;
		}
	}

	.diamondMall_head {
		position: fixed;
		top: 0;
		left: 0;
		z-index: 1000;
		width: 100%;
		height: 100rpx;
		background: #fff;
	}

	.mycustomer_head {
		width: 390rpx;
		text-align: center;
	}

	.mycustomer_bottom {
		width: 100%;
		height: 100rpx;
		background-color: #fff;
		position: fixed;
		bottom: 0;
		left: 0;
	}
</style>
